package io.renren.modules.uploadfile.controller;
import io.netty.util.internal.StringUtil;
import io.renren.common.utils.Constant;
import io.renren.modules.uploadfile.service.FileStorageService;
import io.renren.modules.uploadfile.valueobject.Message;
import io.renren.modules.uploadfile.valueobject.UploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName FileUploadController
 * @Description TODO
 * @Author 树下魅狐
 * @Date 2020/4/28 0028 18:52
 * @Version since 1.0
 **/
@RestController
@RequestMapping("uploadfile/fileupload")
public class FileUploadController {

    @Autowired
    FileStorageService fileStorageService;

    @PostMapping("/upload")
    public ResponseEntity<Message> upload(@RequestParam("file")MultipartFile file, HttpServletRequest request){
        try {
            String url = request.getContextPath() + "/fileStorage/" + fileStorageService.save(file);
            return ResponseEntity.ok(Message.Ok(url, Constant.Success));
        }catch (Exception e){
            return ResponseEntity.badRequest()
                    .body(Message.Fail(e.getMessage()));
        }
    }

    @PostMapping("/uploadimage")
    public Map<String, String> uploadimage(@RequestParam(value = "upfile") MultipartFile upfile, HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        try {
            String url = request.getContextPath() + "/fileStorage/" + fileStorageService.save(upfile);
            map.put("url", url);//这个url是前台回显路径（回显路径为config.json中的imageUrlPrefix+此处的url）
            map.put("state", "SUCCESS");
            map.put("original", "");
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }

    @GetMapping("/files")
    public ResponseEntity<List<UploadFile>> files(){
        List<UploadFile> files = fileStorageService.load()
                .map(path -> {
                    String fileName = path.getFileName().toString();
                    String url = MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class,
                                    "getFile",
                                    path.getFileName().toString()
                            ).build().toString();
                    return new UploadFile(fileName,url);
                }).collect(Collectors.toList());
        return ResponseEntity.ok(files);
    }

    @GetMapping("/files/{filename:.+}")
    public ResponseEntity<Resource> getFile(@PathVariable("filename")String filename){
        Resource file = fileStorageService.load(filename);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment;filename=\""+file.getFilename()+"\"")
                .body(file);
    }
}
